package simple.chat;

import java.util.HashMap;
import com.taurus.core.entity.ITObject;
import com.taurus.core.events.Event;
import com.taurus.core.events.IEventListener;
import com.taurus.core.routes.Routes;
import com.taurus.core.routes.ValidateException;
import com.taurus.permanent.TPServer;
import com.taurus.permanent.core.Extension;
import com.taurus.permanent.core.IValidateListener;
import com.taurus.permanent.core.TPEvents;
import com.taurus.permanent.data.Session;

public class MainServer extends Extension implements IValidateListener{
	HashMap<String,User> users = new HashMap<String, User>();
	
	@Override
	public void configRoute(Routes me) {
		me.add("chat", new ChatController());
		this.setValidateListener(this);
		
		//连接断开时触发
		TPServer.me().getEventManager().addEventListener(TPEvents.EVENT_SESSION_DISCONNECT, new IEventListener() {
			
			@Override
			public void handleEvent(Event event) {
				Session sender = (Session) event.getParameter(TPEvents.PARAM_SESSION);
				String user = (String)sender.getSystemProperty("user");
				synchronized (users) {
					users.remove(user);
				}
			}
		});
	}

	@Override
	public String validate(Session sender,ITObject param) throws ValidateException {
		String user = param.getUtfString("user");
		
		if(user==null) {
			throw new ValidateException("用户为空！");
		}
		
		synchronized (users) {
			if(users.containsKey(user)) {
				throw new ValidateException(user+"已连接！");
			}
			
			User u = new User();
			u.sender = sender;
			u.name = user;
			users.put(user, u);
		}
		
		sender.setSystemProperty("user", user);
		return user;
	}

}
